package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

//    @Value("${qiniu.key.access}")
//    private String accessKey;
//
//    @Value("${qiniu.key.secret}")
//    private String secret;
//
//    @Value("${qiniu.bucket.header.name}")
//    private String headerBucketName;
//
//    @Value("${qiniu.bucket.header.url}")
//    private String headerBucketUrl;

    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage() {
        /**
         * @Author hhwu
         * @Description //TODO 访问个人设置页面
         * @Date 20:17 2022/5/18
         * @Param []
         * @return java.lang.String
         **/

        return "/site/setting";
    }

    @LoginRequired
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        /**
         * @Author hhwu
         * @Description //TODO 访问个人主页页面
         * @Date 20:17 2022/5/18
         * @Param []
         * @return java.lang.String
         **/
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);
        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);
        return "/site/profile";
    }

    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)// 上传文件的请求必须用post
    public String uploadHeader(MultipartFile headerImage, Model model) {// MultipartFile用于获取用户上传的文件
        /**
         * @Author hhwu
         * @Description //TODO 接受用户上传的头像并保存到服务器；更改用户的新头像地址
         * @Date 20:17 2022/5/21
         * @Param []
         * @return java.lang.String
         **/
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片！");
            return "/site/setting";
        }
        String fileName = headerImage.getOriginalFilename();
        model.addAttribute("fileName", fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "图片格式不正确");
            return "/site/setting";
        }
        // 防止各用户上传的文件名重复，修改文件名为随机
        fileName = CommunityUtil.generateUUID() + suffix;
        File dest = new File(uploadPath + "/" + fileName);
        try {
            // 存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败");
            throw new RuntimeException("上传文件失败，服务器发生异常",e);// 将来统一处理异常
        }
        // 更新当前用户的头像路径（web访问路径，而不是服务器路径）
        // http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        /**
         * @Author hhwu
         * @Description //TODO 将服务器上存储的头像和向用户响应的头像链接进行关联
         * @Date 20:17 2022/5/21
         * @Param []
         * @return void
         **/
        // 服务器头像存放路径
        fileName = uploadPath + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("/image" + suffix);// 固定写法
        try (
                FileInputStream fis = new FileInputStream(fileName);// 放在try括号中，结束后会被自动关闭
                ServletOutputStream os = response.getOutputStream();// response被MVC管理，会在请求结束后自动关闭
                ){
            byte[] buffer = new byte[1024];// 创建缓冲区
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {// 如果每次读取到的缓冲区有内容，则写入
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败：" + e.getMessage());
        }
    }

    @RequestMapping(path = "/changepassword", method = RequestMethod.POST)
    public String changePassword(Model model, String oldPassword, String newPassword, String newPassword1) {
        /**
         * @Author hhwu
         * @Description //TODO 修改用户密码，salt不变
         * @Date 20:17 2022/5/21
         * @Param []
         * @return void
         **/
        // 获取当前用户
        User user = hostHolder.getUser();
        // 旧密码不正确时
        if (!user.getPassword().equals(CommunityUtil.md5(oldPassword + user.getSalt()))) {
            model.addAttribute("oldpError", "原密码错误！");
            return "/site/setting";
        }
        // 两次输入的密码不一致
        if (!newPassword.equals(newPassword1)) {
            System.out.println(newPassword+":"+newPassword1);
            model.addAttribute("diffError", "两次输入的密码不一致!");
            return "/site/setting";
        }
        // 如果新密码不符合要求
        if (newPassword == null || newPassword.length() < 6) {
            model.addAttribute("IlleError", "您的新密码不合法！");
            return "/site/setting";
        }
//        还可以限制新密码不能和旧密码相同：oldPassword.equals(newPassword)

                // 对新密码加密,原来的salt不变
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        // 存入新密码
        userService.updatePassword(user.getId(), newPassword);
        return "redirect:/login";// 改完密码后重定向到登录页面
    }


}
